<script setup lang="ts">
  import Header from '@/components/pages/return-factory/index/detail/header/Index.vue'
  import CustomerSendInfo from '@/components/pages/return-factory/index/detail/CustomerSendInfo.vue'
  import CustomerReceiveInfo from '@/components/pages/return-factory/index/detail/CustomerReceiveInfo.vue'
  import OperateLog from '@/components/pages/return-factory/index/detail/OperateLog.vue'
  import ReturnFactoryInfo from '@/components/pages/return-factory/index/detail/ReturnFactoryInfo.vue'
  import GoodList from '@/components/pages/return-factory/index/detail/good-list/Index.vue'
  import LogisticsList from '@/components/pages/return-factory/index/detail/logistics-list/Index.vue'
  import { computed, CSSProperties, nextTick, onMounted, ref } from 'vue'
  import routeComponentName from '@/config/route-component-name'
  import {
    useGetReturnFactoryDetail,
    useGetDetailCustomFieldById,
    useGetReturnFactoryModuleCheckSet,
  } from '@/services/pages/return-factory/useReturnFactory'
  import { useRoute } from 'vue-router'

  const { detail, getDetailLoading, getDetail } = useGetReturnFactoryDetail()
  const {
    customFieldList,
    loading: getDetailCustomFieldLoading,
    getCustomField,
  } = useGetDetailCustomFieldById()
  const {
    loading: getReturnFactoryModuleCheckSetLoading,
    returnFactoryCheckSet,
    getSet: getReturnFactoryModuleCheckSet,
  } = useGetReturnFactoryModuleCheckSet()

  defineOptions({
    name: routeComponentName.returnFactory.returnFactoryDetail,
  })

  // 当前激活的路由对象
  const route = useRoute()

  // 侧边栏是否展开
  const sidebarIsExpand = ref(true)

  // 操作日志组件实例
  const operateLogInstance = ref<InstanceType<typeof OperateLog> | null>(null)

  // 设备列表清单组件实例
  const goodListInstance = ref<InstanceType<typeof GoodList> | null>(null)

  // 物流列表组件实例
  const logisticsListInstance = ref<InstanceType<typeof LogisticsList> | null>(null)

  // 选择的设备列表
  const selectedGoods = ref<Array<ReturnFactoryDetailGood>>([])

  // body样式
  const bodyStyle = computed<CSSProperties>(() => {
    return {
      paddingTop: '0px',
      paddingBottom: '0px',
      paddingLeft: '12px',
      paddingRight: sidebarIsExpand.value ? '0' : '24px',
    }
  })

  // 侧边栏展开收缩按钮样式
  const sidebarExpandBtnStyle = computed<CSSProperties>(() => {
    if (sidebarIsExpand.value) {
      return {
        borderTopRightRadius: '3px',
        borderBottomRightRadius: '3px',
        borderTopLeftRadius: '0px',
        borderBottomLeftRadius: '0px',
      }
    }

    return {
      borderTopLeftRadius: '3px',
      borderBottomLeftRadius: '3px',
      borderTopRightRadius: '0px',
      borderBottomRightRadius: '0px',
    }
  })

  // 公司寄出信息
  const sendInfo = computed(() => {
    return {
      name: detail.value.username,
      phone: detail.value.phone,
      contacts: detail.value.contacts,
      address: `${detail.value.province} ${detail.value.city} ${detail.value.area} ${detail.value.address}`,
    }
  })

  // 公司收货信息
  const receiveInfo = computed(() => {
    const {
      customerReceiveUsername,
      customerReceivePhone,
      customerReceiveProvince,
      customerReceiveCity,
      customerReceiveArea,
      customerReceiveAddress,
      customerTakePieceMode,
    } = detail.value.receiveAddrVo
    return {
      name: customerTakePieceMode === 1 ? '' : customerReceiveUsername,
      phone: customerTakePieceMode === 1 ? '' : customerReceivePhone,
      address:
        customerTakePieceMode === 1
          ? ''
          : `${customerReceiveProvince} ${customerReceiveCity} ${customerReceiveArea} ${customerReceiveAddress}`,
      receiptMethod: customerTakePieceMode,
    }
  })

  // // 返厂信息
  // const returnFactoryInformation = computed(() => {
  //   return {
  //     no: detail.value.repairNo || '',
  //     createTime: detail.value.createTime,
  //     source: detail.value.source,
  //     customerService: detail.value.emp || '',
  //     faultType: detail.value.faultDescr,
  //     desc: detail.value.repairDescr,
  //     imgList: detail.value.images,
  //     enableNetwork: detail.value.enableNetwork,
  //     network: detail.value.network,
  //   }
  // })

  // 加载
  const loading = computed(() => {
    return (
      getDetailLoading.value ||
      getDetailCustomFieldLoading.value ||
      getReturnFactoryModuleCheckSetLoading.value
    )
  })

  /**
   * 更新日志的显示状态
   */
  const onChangeSideBarVisible = () => {
    sidebarIsExpand.value = !sidebarIsExpand.value
    nextTick(() => {
      if (sidebarIsExpand.value && operateLogInstance.value) {
        operateLogInstance.value.getList()
      }
    })
  }

  /**
   * 设备选择事件
   * @param {Array<ReturnFactoryDetailGood>} goods - 设备选择列表
   */
  const handleSelectGood = (goods: Array<ReturnFactoryDetailGood>) => {
    selectedGoods.value = goods
  }

  /**
   * 物流更新事件
   */
  // const handleLogisticsUpdate = async () => {
  //   getDetail(route.params.id as string)
  //   getOperateLog()
  //   getGoodList()
  // }

  /**
   * 获取操作日志
   */
  const getOperateLog = async () => {
    if (operateLogInstance.value) {
      await operateLogInstance.value.getList()
      sidebarIsExpand.value = operateLogInstance.value.total > 0
    }
  }

  /**
   * 获取物流列表
   */
  const getLogisticsList = () => {
    if (logisticsListInstance.value) {
      logisticsListInstance.value.getList()
    }
  }

  /**
   * 获取返厂清单
   */
  const getGoodList = () => {
    if (goodListInstance.value) {
      goodListInstance.value.getList()
    }
  }

  /**
   * 返厂清单更新事件
   */
  const onGoodListUpdate = () => {
    getDetail(route.params.id as string)
    getOperateLog()
    getLogisticsList()
  }

  /**
   * header的更新事件
   */
  const onHeaderUpdate = () => {
    onGoodListUpdate()
    getGoodList()
  }

  onMounted(async () => {
    if (route.params.id) {
      await getDetail(route.params.id as string)
      getCustomField(route.params.id as string)
      getReturnFactoryModuleCheckSet(route.params.id as string)
      getOperateLog()
      getGoodList()
      if ([2, 3].includes(detail.value.status)) {
        getLogisticsList()
      }
    }
  })
</script>

<template>
  <div v-loading="loading" class="return-factory-detail-wrapper">
    <div class="return-factory-detail">
      <div class="header">
        <Header
          :selected-goods="selectedGoods"
          :module-check-method="returnFactoryCheckSet"
          :detail="detail"
          @update="onHeaderUpdate"
        />
      </div>
      <div class="top-divider"></div>
      <div class="body" :style="bodyStyle">
        <div class="main">
          <div class="info-wrapper">
            <!-- 公司寄出信息 -->
            <div class="customer-info">
              <customer-send-info :send-info="sendInfo" />
            </div>

            <!-- 公司收货信息 -->
            <div class="service-report">
              <customer-receive-info :receive-info="receiveInfo" />
            </div>
          </div>

          <!-- 返厂信息 -->
          <div class="base-info">
            <return-factory-info
              :return-factory-info="detail"
              :custom-field-list="customFieldList"
            />
          </div>

          <!-- 返厂清单 -->
          <div class="return-factory-goods">
            <good-list
              ref="goodListInstance"
              :detail="detail"
              :module-check-method="returnFactoryCheckSet"
              @select-good="handleSelectGood"
              @update="onGoodListUpdate"
            />
          </div>

          <!-- 物流信息 -->
          <!-- 先隐藏，后续可能会用到 -->
          <!-- <div class="return-factory-logistics">
            <logistics-list
              ref="logisticsListInstance"
              :return-factory-id="(route.params.id as string) || ''"
              :module-check-method="returnFactoryCheckSet"
              :status="detail.status"
              @update="handleLogisticsUpdate"
            ></logistics-list>
          </div> -->
        </div>
        <div :class="{ 'expand-shrink-btn-wrapper': true, 'sidebar-expand': !sidebarIsExpand }">
          <div
            v-if="sidebarIsExpand"
            class="btn-inner"
            :style="sidebarExpandBtnStyle"
            @click="onChangeSideBarVisible"
          >
            <i class="iconfont icon-retract"></i>
          </div>

          <div
            v-else
            class="btn-inner"
            :style="sidebarExpandBtnStyle"
            @click="onChangeSideBarVisible"
          >
            <i class="iconfont icon-expand"></i>
          </div>
        </div>
        <div v-if="sidebarIsExpand" class="sidebar">
          <operate-log
            ref="operateLogInstance"
            :return-factory-id="(route.params.id as string) || ''"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  @media screen and (max-width: 1570px) {
    .customer-send-receipt-info {
      width: 700px !important;
      flex-direction: row !important;
      column-gap: 48px;

      .customer-info,
      .service-report {
        flex: 1;
      }
    }
  }

  .return-factory-detail-wrapper {
    height: calc(100vh - 92px);
    width: 100%;
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    // 这个定位是用于让侧边栏的展开按钮放到最右边
    position: relative;

    .return-factory-detail {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      display: flex;
      flex-direction: column;

      .top-divider {
        border-bottom: 1px dotted #e5e5e5;
        margin: 12px 0;
      }

      .body {
        flex: 1;
        display: flex;
        height: 0;
        background-color: #fff;
        box-sizing: border-box;

        .main {
          flex: 1;
          box-sizing: border-box;
          width: 0;
          display: flex;
          flex-direction: column;
          row-gap: 48px;
          overflow: auto;

          &::-webkit-scrollbar {
            display: none;
          }

          .info-wrapper {
            display: flex;
            column-gap: 100px;
            flex-wrap: wrap;
            row-gap: 48px;

            .customer-send-receipt-info {
              display: flex;
              flex-direction: column;
              row-gap: 24px;
              width: 300px;
            }

            .base-info {
              flex: 1;
            }
          }
        }

        .expand-shrink-btn-wrapper {
          height: 100%;
          border-left: 1px dotted #e5e5e5;
          box-sizing: border-box;
          margin: 0 4px 0 24px;
          color: $primaryColor;
          display: flex;
          align-items: center;

          .btn-inner {
            background-color: #f1f6fc;
            width: 16px;
            height: 64px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s ease-in;

            .iconfont {
              font-size: 14px;
            }

            &:hover {
              background-color: $primaryColor;

              .iconfont {
                color: #fff;
              }
            }
          }
        }

        .sidebar-expand {
          border: none;
          position: absolute;
          right: 4px;
          top: 0;
          transform: translate(-50%, 0);
          box-sizing: border-box;
          margin: 0;
        }

        .sidebar {
          min-width: 360px;
          max-width: 360px;
          transition: all 0.3s ease-in;
          overflow: hidden;
        }
      }
    }
  }
</style>
